package com.wswy.wzcx.ui.main.garage

import android.graphics.Color
import android.graphics.drawable.ShapeDrawable
import android.support.v4.view.PagerAdapter
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.blankj.utilcode.util.SizeUtils
import com.facebook.drawee.view.SimpleDraweeView
import com.wswy.wzcx.R
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.car.AddCarInfoActivity
import com.wswy.wzcx.ui.car.result.QueryResultActivity
import com.wswy.wzcx.ui.other.ClickUtils
import com.wswy.wzcx.widget.shape.TriangleShape
import kotlin.math.max

class GarageCarsAdapter(val datas:List<UserCarInfo>) : PagerAdapter() ,View.OnClickListener{

    override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`

    private val topSignColors = arrayOf(Color.parseColor("#B30CC79B"),
            Color.parseColor("#B3FA4F2D"),
            Color.parseColor("#B3FFC000"))

    private val bgNoHandleDrawable = HandleStatusDrawable(Color.parseColor("#D2D4D9"),
            Color.parseColor("#80D2D4D9"))
    private val bgNeedHandleDrawable = HandleStatusDrawable(Color.parseColor("#57C7FF"),
            Color.parseColor("#8057C7FF"))

    //更新了的点，修复长度不变数据变了不刷新都问题
    var pendingUpdate = POSITION_UNCHANGED

    private fun getOffsetColor(position: Int):Int{
        val p =  if (position >= topSignColors.size){
            position %  topSignColors.size
        }else{
            max(position,0)
        }
        return topSignColors[p]
    }

    override fun onClick(v: View?) {

        if (ClickUtils.isFastClick()){
            return
        }

        val pos = (v?.getTag(R.id.item_position) as Int?)?:-1
        val userCarInfo = v?.getTag(R.id.item_data) as? UserCarInfo

        when(v?.id){

            R.id.img_edit -> {
                //编辑车辆
                userCarInfo?.let {
                    AddCarInfoActivity.edit(v.context,it)


                    StatTools.sendClick(v.context,StatisticsId.carport_car_edit)

                }

            }
            else -> {
                //点击卡片  查看详情
                userCarInfo?.let {
                    QueryResultActivity.start(v.context, it, pos)

                    StatTools.sendClick(v.context,StatisticsId.carport_car_click)

                }

            }
        }
    }

    override fun getItemPosition(`object`: Any): Int {
        //优化刷新
        val info = ((`object` as? View)?.getTag(R.id.item_data) as? UserCarInfo)

        val p = if (info != null) datas.indexOf(info) else POSITION_NONE

        if (p >=0){
            //修复刷新问题
            if (p == pendingUpdate){

                pendingUpdate = POSITION_UNCHANGED

                return POSITION_NONE
            }

            return p
        }else{
            return POSITION_NONE
        }

    }


    override fun instantiateItem(container: ViewGroup, position: Int): Any {

        val view = getView(position,null,container)

        container.addView(view)

        return view
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        //super.destroyItem(container, position, `object`)

        container.removeView(`object` as View)
    }

     fun getView(position: Int, convertView: View?, container: ViewGroup?): View {
        var layout:View? = convertView
        val viewHolder : ViewHolder

        if (layout == null){
            val inflate = LayoutInflater.from(container?.context).inflate(R.layout.item_layout_garage_car_info, container, false)
            viewHolder = ViewHolder().apply {

                layoutSign = inflate.findViewById(R.id.layout_sign)
                tvSign = inflate.findViewById(R.id.tv_sign_no)
                imgCarIcon = inflate.findViewById(R.id.img_car_icon)

                imgEdit = inflate.findViewById(R.id.img_edit)

                tvCarNo = inflate.findViewById(R.id.tv_car_no)
                tvCarModel = inflate.findViewById(R.id.tv_car_model)
                tvCarFine = inflate.findViewById(R.id.tv_car_fine)
                tvCarPoint = inflate.findViewById(R.id.tv_car_point)
                tvCarFee = inflate.findViewById(R.id.tv_car_fee)

                tvHandleStatus = inflate.findViewById(R.id.tv_handle_status)
            }

            inflate.tag = viewHolder
            layout = inflate
        }else{

            viewHolder = layout.tag as ViewHolder
        }

        datas[position].run {

            viewHolder.imgCarIcon.setImageURI(carExtendInfo?.carTypeData?.series?.logo)

            layout?.setTag(R.id.item_data,this)
            layout?.setTag(R.id.item_position, position)
            layout?.setOnClickListener(this@GarageCarsAdapter)

            viewHolder.imgEdit.setTag(R.id.item_data,this)
            viewHolder.imgEdit.setTag(R.id.item_position, position)
            viewHolder.imgEdit.setOnClickListener(this@GarageCarsAdapter)

            viewHolder.tvCarNo.text = carNo

            this.carExtendInfo?.carTypeData?.run {
                if (!TextUtils.isEmpty(model?.name)){
                    viewHolder.tvCarModel.text = "${brand?.name} ${series?.name}"
                }else{
                    viewHolder.tvCarModel.text = "尚未设置车型"
                }
            }?:kotlin.run {
                viewHolder.tvCarModel.text = "尚未设置车型"
            }

            viewHolder.tvCarFine.text = trafficCount.toString()
            viewHolder.tvCarPoint.text = totalScore.toString()
            viewHolder.tvCarFee.text = totalFee.toString()

            if (totalFee > 0){
                viewHolder.tvHandleStatus.text = "立即代办"
                viewHolder.tvHandleStatus.background =bgNeedHandleDrawable
            }else{
                viewHolder.tvHandleStatus.text = "无需代办"
                viewHolder.tvHandleStatus.background = bgNoHandleDrawable
            }


            (viewHolder.layoutSign.background as? ShapeDrawable)?.run {
                (shape as? TriangleShape)?.setColor(getOffsetColor(position))
                invalidateSelf()
            }?:kotlin.run {
                viewHolder.layoutSign.background = ShapeDrawable(TriangleShape(getOffsetColor(position),SizeUtils.dp2px(6f).toFloat()))
            }

            viewHolder.tvSign.text = "0${position+1}"
        }


        return layout!!
    }

    override fun getCount(): Int = datas.size

    fun getItem(position: Int):UserCarInfo? = datas.getOrNull(position)


    private class ViewHolder {

        lateinit var layoutSign:View
        lateinit var tvSign:TextView

        lateinit var imgCarIcon: SimpleDraweeView

        lateinit var imgEdit : View

        lateinit var tvCarNo : TextView
        lateinit var tvCarModel:TextView

        lateinit var tvCarFine:TextView
        lateinit var tvCarPoint:TextView
        lateinit var tvCarFee:TextView

        lateinit var tvHandleStatus:TextView

    }


}